package au.edu.unsw.infs3634.gamifiedlearning;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.List;

import au.edu.unsw.infs3634.gamifiedlearning.adapter.QuizsListAdapter;
import au.edu.unsw.infs3634.gamifiedlearning.model.QuizModel;
import au.edu.unsw.infs3634.gamifiedlearning.model.UserModel;
import au.edu.unsw.infs3634.gamifiedlearning.utils.FileUtil;
import au.edu.unsw.infs3634.gamifiedlearning.utils.SPUtil;

public class Quiz_home extends AppCompatActivity {
    private UserModel userModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_quiz_home);

        // Back button
        assert getSupportActionBar() != null;
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        RecyclerView rv = findViewById(R.id.rv_list);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
        rv.setLayoutManager(linearLayoutManager);

        int userId = SPUtil.getInt(this, "userId", -1);
        userModel = LitePal.find(UserModel.class, userId);

        QuizsListAdapter adapter = new QuizsListAdapter(this, generateList(), new QuizsListAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(QuizModel model) {
                Intent intentQuiz = new Intent(Quiz_home.this, Quiz_question.class);
                intentQuiz.putExtra(Quiz_question.continent, model.getName());
                intentQuiz.putExtra("id", model.getId());
                intentQuiz.putParcelableArrayListExtra("questionList", (ArrayList<? extends Parcelable>) model.getQuestionList());
                startActivity(intentQuiz);
            }
        });
        rv.setAdapter(adapter);
    }

    @Override
    protected void onResume() {
        super.onResume();
        int userId = SPUtil.getInt(this, "userId", -1);
        userModel = LitePal.find(UserModel.class, userId);
    }

    private List<QuizModel> generateList() {
        String json = FileUtil.readAssetsFileToString("data.json", this);
        List<QuizModel> list = new Gson().fromJson(json, new TypeToken<List<QuizModel>>() {
        }.getType());
        return list;
    }

    //Back button
    @Override
    public boolean onSupportNavigateUp() {
        finish();
        return true;
    }
}